package com.talkweb.osmharmony.tileprovider.tilesource.bing;

import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONObject;

/**
 * ImageryMetaData storage. Class used to decode valid ImageryMetaData.
 */
public class ImageryMetaData {

    // Useful fields found in ImageryMetaData response
    private final static String STATUS_CODE = "statusCode";
    private final static String AUTH_RESULT_CODE = "authenticationResultCode";
    private final static String AUTH_RESULT_CODE_VALID = "ValidCredentials";
    private final static String RESOURCE_SETS = "resourceSets";
    private final static String ESTIMATED_TOTAL = "estimatedTotal";
    private final static String RESOURCE = "resources";

    /**
     * Parse a JSON string containing ImageryMetaData response
     *
     * @param a_jsonContent the JSON content string
     * @throws Exception
     * @return ImageryMetaDataResource object containing parsed information
     */
    static public ImageryMetaDataResource getInstanceFromJSON(final String a_jsonContent) throws Exception {

        if (a_jsonContent == null) {
            throw new Exception("JSON to parse is null");
        }

        /// response code should be 200 and authorization should be valid (valid BingMap key)
        final ZSONObject jsonResult = ZSONObject.stringToZSON(a_jsonContent);
        final int statusCode = jsonResult.getIntValue(STATUS_CODE);
        if (statusCode != 200) {
            throw new Exception("Status code = " + statusCode);
        }

        if (AUTH_RESULT_CODE_VALID.compareToIgnoreCase(jsonResult.getString(AUTH_RESULT_CODE)) != 0) {
            throw new Exception("authentication result code = " + jsonResult.getString(AUTH_RESULT_CODE));
        }

        // get first valid resource information
        final ZSONArray resultsSet = jsonResult.getZSONArray(RESOURCE_SETS);
        if (resultsSet == null || resultsSet.isEmpty()) {
            throw new Exception("No results set found in json response");
        }

        if (resultsSet.getZSONObject(0).getIntValue(ESTIMATED_TOTAL) <= 0) {
            throw new Exception("No resource found in json response");
        }

        final ZSONObject resource = resultsSet.getZSONObject(0).getZSONArray(RESOURCE).getZSONObject(0);

        return ImageryMetaDataResource.getInstanceFromJSON(resource, jsonResult);
    }

}
